<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Skornyakov Anatoliy
 * Date: 01.06.13
 * Time: 14:25
 * 
 */

class Zftest_Model_DbTable_Users extends Zftest_Model_DbTable
{
    protected $_name = 'users';

    public function getList(Zend_Db_Table_Select $select = null)
    {
        if (is_null($select)) {
            $select = $this->select();
        }
        $select->from($this, array('name', 'surname', 'phoneCountry', 'phoneCity', 'phoneNumber', 'phoneMore', 'userId'))->order('surname');

        return $this->fetchAll($select);
    }

    public function getById($userId)
    {
        $select = $this->select()->where('userId = ?', $userId);

        return $this->fetchRow($select);
    }

    public function add($values)
    {
        $values = $this->_normalizationData($values);

        return $this->insert($values);
    }

    public function update($values, $userId)
    {
        $values = $this->_normalizationData($values);

        return parent::update($values, array('userId = ?' => $userId));
    }

    private function _normalizationData($values)
    {
        if (isset($values['phone'])) {
            if (is_array($values['phone'])) {
                $phone = $values['phone'];

                foreach ($phone as $key => $value) {
                    $values['phone' . ucfirst($key)] = $value;
                }
            }
            unset($values['phone']);
        }

        return $values;
    }
}